<!-- 回款列表 -->

<template>
  <div class="client-list">
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    </pageHeader>
    <div class="sales-order">
      <a-tabs v-model="getListType" @change="getSearchType" type="line">
        <a-tab-pane :key="3" title="全部汇款"> </a-tab-pane>
        <a-tab-pane :key="4" title="我的汇款"> </a-tab-pane>
      </a-tabs>
    </div>
    <div class="search-box" style="padding: 10px">
      <div>
        <a-space>
          <a-input-search
            @change="Search"
            v-model="NumberSearch"
            :style="{ width: '320px' }"
            placeholder="请输入订单编号"
            search-button
          />
          <a-button type="outline" @click="reset">
            <template #icon> <icon-refresh /> </template>重置</a-button
          ></a-space
        >
      </div>
      <div>
        <a-space>
          <a-button status="success" @click="getDeriveData">
            <template #icon>
              <icon-export rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>
          <a-button type="primary" @click="showFormHeaderSetting"
            >表头设置</a-button
          >
        </a-space>
      </div>
    </div>
    <div style="padding: 0px 10px">
      <TableTurn :table-data="getData" ref="tableRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          v-for="item in selectedHeader"
          :title="item.name"
          :data-index="item.code"
          :key="item.code"
          :width="200"
          align="center"
        >
          <!-- 计划开始时间 -->
          <template v-if="item.code === 'createdAt'" #cell="{ record }">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <!-- 订单状态 -->
          <template v-else-if="item.code === 'okState'" #cell="{ record }">
            <div
              class="status"
              :style="{
                color: orderExecuteStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
              }"
            >
              <p
                :style="{
                  'background': orderExecuteStatus.filter(
                    (ele) => ele.id === record.state
                  )[0]?.backgroundColor,
                  'box-shadow': `0px 0px 5px`,
                }"
              ></p>
              {{
                orderExecuteStatus.filter((ele) => ele.id === record.state)[0]
                  ?.value
              }}
            </div>
          </template>
        </a-table-column>
        <a-table-column align="center" :width="150" title="回款与发票详情">
          <template #cell="{ record }">
            <a-tooltip content="查看详情">
              <IconFont
                type="icon-details-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDetail(record.id)"
              />
            </a-tooltip>
          </template>
        </a-table-column>
        <a-table-column :width="150" fixed="right" title="操作" align="center">
          <template #title> 操作 </template>
          <template #cell="{ record }">
            <a-tooltip
              v-if="record.userStaffId === userInfo.id"
              content="回款录入"
            >
              <IconFont
                type="icon-huikuanfangshi-copy"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="enter(record)"
              />
            </a-tooltip>

            <a-tooltip
              v-if="record.userStaffId === userInfo.id"
              content="发票录入"
            >
              <IconFont
                type="icon-fapiao"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="Invoice(record)"
              />
            </a-tooltip>
          </template>
        </a-table-column>
      </TableTurn>
    </div>
    <FormHeaderSetting
      v-model:visible="formHeaderSettingVisible"
      title="回款列表表头设置"
      :resultList="headerSetting.list"
      @headerSave="headerSave"
    ></FormHeaderSetting>

    <returnedMoneyEnter
      v-if="enterVisible"
      v-model:visible="enterVisible"
      :currForm="currForm"
      :orderId="orderId"
      @editReturnedEmit="editReturnedEmit"
    ></returnedMoneyEnter>
    <invoiceInfo
      v-if="invoiceVisible"
      v-model:visible="invoiceVisible"
      :clientId="clientId"
      :orderId="orderId"
      :currForm="form"
      @editinvoiceInfo="editinvoiceInfo"
    ></invoiceInfo>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import {
    GetHeaderSettings,
    putHeaderSettings,
    GetClientOrder,
  } from '@/api/order-management/client-order';
  import { formHeaderSetting } from '@/types/global';
  import dayjs from 'dayjs';
  import {
    PostInvoiceInfo,
    PostCollectionInfo,
    GetCollectionDeriveExcel,
  } from '@/api/order-management/returned-management/base-setting/index';
  import returnedMoneyEnter from './components/returned-money-enter/index.vue';
  import invoiceInfo from './components/invoice-information/index.vue';

  const router = useRouter();
  const title = '回款列表';
  const breadCrumb = ['订单管理', '回款管理', '回款列表'];
  const getListType = ref(3);
  const headerSetting = reactive<any>({
    list: [],
  });

  let form = reactive({});
  const orderId = ref();
  const clientId = ref();
  const invoiceVisible = ref(false);
  let enterVisible = ref(false); // 判断用户是否点击录入按钮
  const NumberSearch = ref();
  const userInfo = JSON.parse(sessionStorage.getItem('loginInfo'));

  let tableRef = ref(); // 储存table的ref

  const orderExecuteStatus = [
    { id: 1, value: '待执行', backgroundColor: '#4e8bfb' },
    { id: 2, value: '待执行', backgroundColor: '#4e8bfb' },
    { id: 3, value: '执行中', backgroundColor: '#4e8bfb' },
    { id: 4, value: '已完成', backgroundColor: '#009933' },
  ];

  // 获取回款列表数据
  const getData = async (pageData?: any) => {
    try {
      let msg: any = {};
      if (NumberSearch.value) msg.number = NumberSearch.value;
      const res = await GetClientOrder({
        ...pageData,
        collectionList: 1,
        ...msg,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const columns = [
    {
      name: '订单编号',
      code: 'number',
      isDefault: 1,
    },
    {
      name: '客户名称',
      code: 'clientCompanyName',
      isDefault: 1,
    },
    {
      name: '客户联系人',
      code: 'customerName',
      isDefault: 1,
    },
    {
      name: '客户联系电话',
      code: 'customerPhone',
      isDefault: 1,
    },
    {
      name: '业务员',
      code: 'userStaffName',
      isDefault: 1,
    },
    {
      name: '订单总金额（人民币）',
      code: 'totalPrice',
      isDefault: 1,
    },
    {
      name: '订单创建时间',
      code: 'createdAt',
      isDefault: 1,
    },
    {
      name: '应收账款总额（人民币）',
      code: 'receivablePrice',
      isDefault: 1,
    },
    {
      name: '累计回款金额（人民币）',
      code: 'accumulatedCollectionPrice',
      isDefault: 1,
    },
    {
      name: '未回款金额（人民币）',
      code: 'waitCollectionPrice',
      isDefault: 1,
    },
    {
      name: '已开票金额（人民币）',
      code: 'invoicedPrice',
      isDefault: 1,
    },
    {
      name: '可开票金额（人民币）',
      code: 'invoicablePrice',
      isDefault: 1,
    },
    {
      name: '订单状态',
      code: 'okState',
      isDefault: 1,
    },
  ];

  // 获取表头数据
  const getHeaders = async (listType = 3) => {
    try {
      const res = await GetHeaderSettings({ listType });
      headerSetting.list = res.extends ? res.extends : columns;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: formHeaderSetting['list'] = [];
    headerSetting.list.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      // const data = {
      //   extend: JSON.stringify(headerList),
      //   listType: getListType.value,
      // };
      await putHeaderSettings({
        extend: JSON.stringify(headerList),
        listType: getListType.value,
      });
      headerSetting.list = [...headerList];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const getSearchType = (key: number) => {
    getListType.value = key;
    getHeaders(key);
  };

  // 查看详情按钮
  const goDetail = (id: any) => {
    router.push({
      name: 'ReturnedDetail',
      query: {
        id,
      },
    });
  };

  let currForm = ref(); // 储存当前行数据

  // 录入按钮事件
  const enter = (record?: any) => {
    currForm.value = record;
    orderId.value = record.id;
    enterVisible.value = true;
  };

  // 录入按钮返回来的自定义事件
  const editReturnedEmit = async (formData: any) => {
    // let msg = ref(JSON.parse(JSON.stringify(formData)));
    formData.orderId = formData.id;
    formData.accountId = formData.collectionAccountId;
    delete formData.collectionAccountId;
    delete formData.id;
    await PostCollectionInfo({
      ...formData,
    });
    tableRef.value.loadData();
  };

  const Invoice = (record: any) => {
    invoiceVisible.value = true;
    clientId.value = record.clientCompanyId;
    form = {
      orderId: undefined, //订单id
      collectionTypeId: undefined, //回款类型id
      invoiceNumber: '', //发票编号
      InvoiceTypeId: undefined, //发票类型Id
      invoicingTime: undefined, //开票时间
      invoicingPrice: undefined, //开票金额
      invoicingPriceUnit: '', //开票金额单位
      invoicingSubject: '', //开票科目
      invoicingUserId: undefined, //开票人
      invoiceMessageId: undefined, //发票凭证文件id
      invoiceProofFileId: undefined, //订单id
      TaxRate: '',
    };
    orderId.value = record.id;
  };

  const editinvoiceInfo = async (formData) => {
    await PostInvoiceInfo({ ...formData });
    tableRef.value.loadData();
  };
  const getDeriveData = () => {
    GetCollectionDeriveExcel('回款模板');
  };

  const Search = () => {
    tableRef.value.loadData();
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableRef.value.loadData();
    }
  };
  // 重置按钮
  const reset = () => {
    NumberSearch.value = '';
    tableRef.value.loadData();
  };
</script>

<style scoped lang="less">
  // .client-list {
  //   :deep(.arco-space) {
  //     // justify-content: space-between;
  //   }
  //   :deep(.arco-space-horizontal .arco-space-item) {
  //     // margin-left: 50px;
  //   }

  //   &-header {
  //     // width: 100%;
  //     // margin-bottom: 10px;
  //     // margin-top: 5px;
  //     :deep(.arco-btn-secondary) {
  //       // color: #165dff;
  //       // margin-right: 20px;
  //     }
  //   }
  // }
  // :deep(.arco-table-tr) {
  //   height: 60px;
  // }
  .search-box {
    // margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
  }

  .use-state {
    display: flex;
    justify-content: center;
    text-align: center;
  }
  .cycle {
    position: relative;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    content: '';
    display: inline-block;
    top: 3px;
    right: 10px;
  }

  .blueColor {
    color: #156dff;
  }
  .blueColor-cycle {
    background-color: #156dff;
  }
  // 已通过
  .greenColor {
    color: #31c273;
  }
  .greenColor-cycle {
    background-color: #31c273;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
